<?php
/**
 * Created by PhpStorm.
 * User: Ysll <754060604@qq.com>
 * Date: 2017/10/11
 * Time: 10:57
 */

namespace Home\Controller;


use Common\Common\Validator;
use Think\Controller;

class FormController extends Controller
{
    public function insertLeaveWord()
    {
        if (IS_POST) {
            $validator = Validator::make($_POST, [
                'name' => 'required|min:2|max:32',
                'qq' => 'required|integer|min:4',
                'tel' => 'required|max:32|min:4',
                'email' => 'required|email',
                'comment' => 'required|max:255',
                'code' => ['required', 'max:4', 'min:4', 'code']
            ]);
            if ($validator->filed()) {
                $this->error('数据错误', '/home/contact', false, $validator);
            }
            $data = array_only($_POST, [
                'name', 'qq', 'tel', 'email', 'comment'
            ]);
            if (M('leave_word')->add($data)) {
                $this->success('提交成功');
            } else {
                $this->error('创建失败');
            }

        } else {
            $this->error('请求错误');
        }
    }

    protected function error($message = '', $jumpUrl = '', $ajax = false, Validator $validator = null)
    {
        $temp = '';
        if ($validator != null && $validator->filed()) {
            foreach ($validator->error() as $key => $error) {
                $temp .= "<ul style='list-style: none'><p>$key:</p>";
                foreach ($error as $item) {
                    $temp .= "<li style='margin-left: 20px; color: red'>$item</li>";
                }
                $temp .= '</ul>';
            }
        }
        parent::error($temp . $message, $jumpUrl, $ajax);
    }
}